package com.example.spring_3.ch03.mapper;

import com.example.spring_3.ch03.pojo.SysUser;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface UserRepository extends JpaRepository<SysUser,Long> {
    /**
     * 根据用户名查询用户
     * @param usrName
     * @return
     */
    public List<SysUser>findByUsrName(String usrName);

    /**
     * 加关键字查询
     * @param usrName
     * @return
     */
    public List<SysUser>findByUsrNameAndUsrPassword(String usrName , String usrPassword);

    /**
     * 修改、删除。统计
     * @param usrName
     * @return
     */
    public Long countByUsrName(String usrName);

    public List<SysUser>findByUsrNameLike(String usrName);

//    @Query("select u from SysUser u where u.usrRoleId = ?1")
//    public List<SysUser>findByUsrRoleId(Long roleId);

//    @Query(value = "select * from sys_user where usr_role_id=?1" , nativeQuery = true)
//    public List<SysUser>findByUsrRoleId(Long roleId);

    @Query("select u from SysUser u where u.usrRoleId = :roleId")
    public List<SysUser>findByUsrRoleId(@Param("roleId") Long roleId);

    @Transactional(timeout = 10)
    @Modifying
    @Query("update SysUser u set u.usrName = ?1 where u.usrId = ?2")
    public int modifyNameById(String usrName , Long usrId);

    public List<SysUser>findByUsersByName(String userName);

    @Query("select u from SysUser u where u.usrRoleId = ?1 ")
    public Page<SysUser> findPageByUserRoleId(Long roleId , Pageable pageable);

    Page<SysUser> findPageByMap(Specification<SysUser> sysUserSpecification);


    //第三章
    @Query("select  u.usrId as usrId , u.usrName as usrName , u.usrPassword as usrPassword, " +
            "u.usrRoleId as usrRoleId , u.usrFlag as usrFlag , r.roleName as roleName from SysUser " +
            "u , SysRole r where u.usrRoleId = r.roleId and u.usrId = ?1")
    UserInfo getSysUserInfo(Long usrId);
}
